#!/bin/sh
#
# OpenIPC.org | 2024
#

MODULE=/lib/modules/4.9.84/sigmastar

detect_sensor() {
	insmod $MODULE/sensor_config.ko
	if [ -e /dev/srcfg ]; then
		echo srcfg 0 1 0 0 0 0 > /dev/srcfg
		rmmod sensor_config
	fi
	SENSOR=$(ipcinfo -s)
}

set_sensor() {
	case $SENSOR in
		imx307|imx335|imx347|imx415)
			insmod $MODULE/sensor_${SENSOR}_mipi.ko chmap=1
			;;
		*)
			echo -e "\n\e[1;31mUNSUPPORTED sensor - $SENSOR\e[0m\n" | logger -s -t OpenIPC
			;;
	esac
}

insert_ko() {
	insmod $MODULE/mhal.ko
	insmod $MODULE/mi_common.ko
	insmod $MODULE/mi_sys.ko cmdQBufSize=768 logBufSize=256
	insmod $MODULE/mi_rgn.ko
	insmod $MODULE/mi_ldc.ko
	insmod $MODULE/mi_ai.ko
	insmod $MODULE/mi_ao.ko
	insmod $MODULE/mi_mipitx.ko
	insmod $MODULE/mi_sensor.ko
	insmod $MODULE/mi_shadow.ko
	insmod $MODULE/mi_divp.ko
	insmod $MODULE/mi_vif.ko
	insmod $MODULE/mi_vpe.ko
	insmod $MODULE/mi_venc.ko fw_path=/etc/firmware/chagall.bin

	MAJOR=$(awk '$2=="mi_poll" {print $1}' /proc/devices)
	mknod /dev/mi_poll c "$MAJOR" 0
	echo isproot /etc/firmware > /dev/ispmid
}

if [ ! -e /sys/module/mi_common ]; then
	insert_ko
fi

echo -e "\n\e[1;33mAutodetect sensor\e[0m\n" | logger -s -t OpenIPC
detect_sensor

if [ -z "$SENSOR" ]; then
	echo -e "\n\e[1;31mSensor parameter MISSING\e[0m\n" | logger -s -t OpenIPC
	exit 1
fi

DRIVER=$(ls /sys/module | grep $SENSOR)
if [ -n "$DRIVER" ]; then
	rmmod $DRIVER
fi

echo -e "\n\e[1;32mSensor assigned - $SENSOR\e[0m\n" | logger -s -t OpenIPC
set_sensor

# Custom settings
gpio set 29

exit 0
